/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-dealer
*
* @File name : MaintainService.java
*
* @Author : Administrator
*
* @Date : 2017年12月5日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年12月5日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/
	
package com.yonyou.gmmc.service.dealer.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dto.maintain.ReservationDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yonyou.gmmc.service.dealer.dao.TmUsersMapper;
import com.yonyou.gmmc.service.dealer.dao.TtReservationMapper;
import com.yonyou.gmmc.service.dealer.dao.TtReservationRecordMapper;
import com.yonyou.gmmc.service.dealer.model.MaintainInfoList;
import com.yonyou.gmmc.service.dealer.model.TmUsers;
import com.yonyou.gmmc.service.dealer.model.TtReservation;
import com.yonyou.gmmc.service.dealer.model.TtReservationRecord;


/**
*
* @author Administrator
* @date 2017年12月5日
*/

@Service
@Transactional
public class MaintainService {

    private Logger logger = Logger.getLogger(MaintainService.class);
    
    @Autowired
    private TtReservationMapper ttReservationMapper;
    
    @Autowired
    private TtReservationRecordMapper ttReservationRecordMapper;
    
    @Autowired
    private TmUsersMapper tmUsersMapper;
    
    
    public List<TmUsers> queryTmUsersList(String phone){
		try{
			/*Example example = new Example(TrUserEnterprise.class);
        	Criteria criteria = example.createCriteria();
    		criteria.andEqualTo("phone", phone);*/
        	List<TmUsers> tmUsersList = tmUsersMapper.queryTmUsersList(phone);
            return tmUsersList;
		}catch (Exception e){
	        logger.error(e.getMessage());
	        throw new ServiceBizException(e.getMessage(), e);
	    }
	}
    
    @SuppressWarnings("unused")
    public PageInfo<TtReservation> maintainRecords(Map<String,Object> query) throws Exception{
        List<TtReservation> resultList = new ArrayList<TtReservation>();
        try{
        	//判断售后顾问是否存在
        	String phone = query.get("phone").toString();
        	List<TmUsers> tmUsersList = queryTmUsersList(phone);
        	if(CheckUtil.NullOrEmpty(tmUsersList)){
        		//用户不存在
        		throw new ServiceBizException("用户不存在！");
        	}else if(tmUsersList.size()>1){
        		//用户存在多条数据
        		throw new ServiceBizException("用户信息错误！");
        	}
        	query.put("userId", tmUsersList.get(0).getUserId());
        	
        	String flag = query.get("flag").toString();
            Page<TtReservation> ss = PageHelper.startPage(Integer.parseInt(query.get("pageNum").toString()),
                                                          Integer.parseInt(query.get("pageSize").toString()));
            if(flag.equals("1")){
                logger.info("查询今日养修");
                resultList = ttReservationMapper.selectMaintainToday(query);
            }else if(flag.equals("2")){
                logger.info("查询待确认养修");
                resultList = ttReservationMapper.selectMaintainNotSure(query);
            }else{
                logger.info("查询全部养修");
                resultList = ttReservationMapper.selectMaintain(query);
            }
            PageInfo<TtReservation> page = new PageInfo<TtReservation>(resultList);
            return page;
        }catch (Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
    
    public MaintainInfoList maintainInfo(String flag,String phone,String resnId) throws Exception{
        MaintainInfoList result = new MaintainInfoList();
        try{
        	//判断是否
        	List<TmUsers> tmUsersList = queryTmUsersList(phone);
        	if(CheckUtil.NullOrEmpty(tmUsersList)){
        		//用户不存在
        		throw new ServiceBizException("用户不存在！");
        	}else if(tmUsersList.size()>1){
        		//用户存在多条数据
        		throw new ServiceBizException("用户信息错误！");
        	}
        	Long userId = tmUsersList.get(0).getUserId().longValue();
            Map<String,Object> query = new HashMap<String,Object>();
            query.put("userId", tmUsersList.get(0).getUserId());
            query.put("flag", flag);
            query.put("phone", phone);
            query.put("resnId", resnId);
            List<ReservationDto> list = new ArrayList<ReservationDto>();
            logger.info("flag="+flag);
            if(flag=="1"||flag.equals("1")){
            	logger.info("flag="+flag);
            	list = ttReservationMapper.selectMaintainInfo(query);
            }else if(flag=="2"||flag.equals("2")){
            	list = ttReservationMapper.selectInfoAndRecord(query);
            }
            if(!CheckUtil.NullOrEmpty(list)){
            	Long consultantId = list.get(0).getSalesConsultantId();
            	if(consultantId.equals(userId)){
            		list.get(0).setIsOwner(true);
            	}else{
            		list.get(0).setIsOwner(false);
            	}
                result.setList(list);
            }
            return result;
        }catch (Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

	public Map<String, Object> affirmMaintain(TtReservation ttReservation, String phone) {
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			//判断是否
        	List<TmUsers> tmUsersList = queryTmUsersList(phone);
        	if(CheckUtil.NullOrEmpty(tmUsersList)){
        		//用户不存在
        		throw new ServiceBizException("用户不存在！");
        	}else if(tmUsersList.size()>1){
        		//用户存在多条数据
        		throw new ServiceBizException("用户信息错误！");
        	}
        	
        	Integer resnId = ttReservation.getResnId();
        	TtReservation reservationResult = ttReservationMapper.selectByResnId(resnId);
        	Long userId = tmUsersList.get(0).getUserId().longValue();
        	if(!CheckUtil.NullOrEmpty(reservationResult)){
        		Long consultantId = reservationResult.getSalesConsultantId();
        		if(consultantId.equals(userId)){
        			if(reservationResult.getApplyStatus()==10021006){
            			Date newDate = new Date();
            			//更新预约信息
            			TtReservation record = new TtReservation();
            			record.setResnId(ttReservation.getResnId());
            			record.setApplyStatus(10021002);
            			if(!CheckUtil.NullOrEmpty(ttReservation.getAppointType())){
            				record.setAppointType(ttReservation.getAppointType());
            			}
            			if(!CheckUtil.NullOrEmpty(ttReservation.getReseApplStartTime())){
            				record.setReseApplStartTime(ttReservation.getReseApplStartTime());
            			}
//            			record.setSalesConsultantId(tmUsersList.get(0).getUserId().longValue());
            			record.setUpdateDate(newDate);
            			record.setUpdateBy(tmUsersList.get(0).getUserId().longValue());
            			int a = ttReservationMapper.updateByPrimaryKeySelective(record);
            			
            			//插入确认预约信息
            			TtReservationRecord ttReservationRecord = new TtReservationRecord();
            			ttReservationRecord.setResnId(ttReservation.getResnId().longValue());
            			ttReservationRecord.setRecordKind(1);
            			ttReservationRecord.setRecordRemark(ttReservation.getRemarks());
            			ttReservationRecord.setCreateDate(newDate);
            			ttReservationRecord.setCreateBy(tmUsersList.get(0).getUserId().longValue());
            			int b = ttReservationRecordMapper.insertSelective(ttReservationRecord);
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_SUCCESS);
            			result.put(ResultMsgConstants.RESULT_MESSAGE, "确认预约成功！");
            		}else{
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
            			result.put(ResultMsgConstants.ERR_MSG, "状态错误，不能确认预约！");
            		}
        		}else{
        			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
        			result.put(ResultMsgConstants.ERR_MSG, "顾问信息错误，不能确认预约！");
        		}
        	}else{
        		result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
    			result.put(ResultMsgConstants.ERR_MSG, "预约信息不存在！");
    		}
        	
			return result;
		}catch (Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
	}
	
	public Map<String, Object> recordMaintain(TtReservation ttReservation, String phone) {
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			//判断是否
        	List<TmUsers> tmUsersList = queryTmUsersList(phone);
        	if(CheckUtil.NullOrEmpty(tmUsersList)){
        		//用户不存在
        		throw new ServiceBizException("用户不存在！");
        	}else if(tmUsersList.size()>1){
        		//用户存在多条数据
        		throw new ServiceBizException("用户信息错误！");
        	}
        	
        	Integer resnId = ttReservation.getResnId();
        	TtReservation reservationResult = ttReservationMapper.selectByResnId(resnId);
        	Long userId = tmUsersList.get(0).getUserId().longValue();
        	if(!CheckUtil.NullOrEmpty(reservationResult)){
        		Long consultantId = reservationResult.getSalesConsultantId();
        		if(consultantId.equals(userId)){
        			if(reservationResult.getApplyStatus()==10021002){
            			Date newDate = new Date();
            			//插入跟进记录信息
            			TtReservationRecord ttReservationRecord = new TtReservationRecord();
            			ttReservationRecord.setResnId(ttReservation.getResnId().longValue());
            			ttReservationRecord.setRecordKind(2);
            			ttReservationRecord.setRecordRemark(ttReservation.getRemarks());
            			ttReservationRecord.setCreateDate(newDate);
            			ttReservationRecord.setCreateBy(tmUsersList.get(0).getUserId().longValue());
            			int b = ttReservationRecordMapper.insertSelective(ttReservationRecord);
            			
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_SUCCESS);
            			result.put(ResultMsgConstants.RESULT_MESSAGE, "添加跟进记录成功！");
            		}else{
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
            			result.put(ResultMsgConstants.ERR_MSG, "状态错误，不能添加跟进记录！");
            		}
        		}else{
        			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
        			result.put(ResultMsgConstants.ERR_MSG, "顾问信息错误，不能添加跟进记录！");
        		}
        	}else{
        		result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
    			result.put(ResultMsgConstants.ERR_MSG, "预约信息不存在！");
    		}
        	
			return result;
		}catch (Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
	}
	
	public Map<String, Object> arriveMaintain(TtReservation ttReservation, String phone) {
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			//判断是否
        	List<TmUsers> tmUsersList = queryTmUsersList(phone);
        	if(CheckUtil.NullOrEmpty(tmUsersList)){
        		//用户不存在
        		throw new ServiceBizException("用户不存在！");
        	}else if(tmUsersList.size()>1){
        		//用户存在多条数据
        		throw new ServiceBizException("用户信息错误！");
        	}
        	
        	Integer resnId = ttReservation.getResnId();
        	TtReservation reservationResult = ttReservationMapper.selectByResnId(resnId);
        	Long userId = tmUsersList.get(0).getUserId().longValue();
        	if(!CheckUtil.NullOrEmpty(reservationResult)){
        		Long consultantId = reservationResult.getSalesConsultantId();
        		if(consultantId.equals(userId)){
        			if(reservationResult.getApplyStatus()==10021002){
            			Date newDate = new Date();
                    	TtReservation record = new TtReservation();
            			record.setResnId(ttReservation.getResnId());
            			record.setApplyStatus(10021003);
            			record.setUpdateDate(newDate);
            			record.setUpdateBy(tmUsersList.get(0).getUserId().longValue());
            			int a = ttReservationMapper.updateByPrimaryKeySelective(record);
            			//插入确认到店信息
            			TtReservationRecord ttReservationRecord = new TtReservationRecord();
            			ttReservationRecord.setResnId(ttReservation.getResnId().longValue());
            			ttReservationRecord.setRecordKind(3);
            			ttReservationRecord.setRecordRemark(ttReservation.getRemarks());
            			ttReservationRecord.setCreateDate(newDate);
            			ttReservationRecord.setCreateBy(tmUsersList.get(0).getUserId().longValue());
            			int b = ttReservationRecordMapper.insertSelective(ttReservationRecord);
            			
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_SUCCESS);
            			result.put(ResultMsgConstants.RESULT_MESSAGE, "确认到店成功！");
            		}else{
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
            			result.put(ResultMsgConstants.ERR_MSG, "状态错误，不能确认到店！");
            		}
        		}else{
        			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
        			result.put(ResultMsgConstants.ERR_MSG, "顾问信息错误，不能确认到店！");
        		}
        	}else{
        		result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
    			result.put(ResultMsgConstants.ERR_MSG, "预约信息不存在！");
    		}
        	
			return result;
		}catch (Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
	}
	
	
	public Map<String, Object> cancleMaintain(TtReservation ttReservation, String phone) {
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			//判断是否
        	List<TmUsers> tmUsersList = queryTmUsersList(phone);
        	if(CheckUtil.NullOrEmpty(tmUsersList)){
        		//用户不存在
        		throw new ServiceBizException("用户不存在！");
        	}else if(tmUsersList.size()>1){
        		//用户存在多条数据
        		throw new ServiceBizException("用户信息错误！");
        	}
        	Integer resnId = ttReservation.getResnId();
        	TtReservation reservationResult = ttReservationMapper.selectByResnId(resnId);
        	Long userId = tmUsersList.get(0).getUserId().longValue();
        	if(!CheckUtil.NullOrEmpty(reservationResult)){
        		Long consultantId = reservationResult.getSalesConsultantId();
        		if(consultantId.equals(userId)){
        			if(reservationResult.getApplyStatus()==10021002){
            			Date newDate = new Date();
                    	TtReservation record = new TtReservation();
            			record.setResnId(ttReservation.getResnId());
            			record.setApplyStatus(10021004);
            			record.setUpdateDate(newDate);
            			record.setUpdateBy(tmUsersList.get(0).getUserId().longValue());
            			int a = ttReservationMapper.updateByPrimaryKeySelective(record);
            			
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_SUCCESS);
            			result.put(ResultMsgConstants.RESULT_MESSAGE, "取消预约成功！");
            		}else{
            			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
            			result.put(ResultMsgConstants.ERR_MSG, "状态错误，不能取消预约！");
            		}
        		}else{
        			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
        			result.put(ResultMsgConstants.ERR_MSG, "顾问信息错误，不能取消预约！");
        		}
        	}else{
        		result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
    			result.put(ResultMsgConstants.ERR_MSG, "预约信息不存在！");
    		}
        	
			return result;
		}catch (Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
	}
	
	
	public Map<String, Object> disposeMaintain(TtReservation ttReservation, String phone) {
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			//判断是否
        	List<TmUsers> tmUsersList = queryTmUsersList(phone);
        	if(CheckUtil.NullOrEmpty(tmUsersList)){
        		//用户不存在
        		throw new ServiceBizException("用户不存在！");
        	}else if(tmUsersList.size()>1){
        		//用户存在多条数据
        		throw new ServiceBizException("用户信息错误！");
        	}
        	Integer resnId = ttReservation.getResnId();
        	TtReservation reservationResult = ttReservationMapper.selectByResnId(resnId);
        	if(!CheckUtil.NullOrEmpty(reservationResult)){
    			if(reservationResult.getApplyStatus()==10021001){
        			Date newDate = new Date();
                	TtReservation record = new TtReservation();
        			record.setResnId(ttReservation.getResnId());
        			record.setApplyStatus(10021006);
        			record.setSalesConsultantId(tmUsersList.get(0).getUserId().longValue());
        			record.setUpdateDate(newDate);
        			record.setUpdateBy(tmUsersList.get(0).getUserId().longValue());
        			int a = ttReservationMapper.updateByPrimaryKeySelective(record);
        			
        			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_SUCCESS);
        			result.put(ResultMsgConstants.RESULT_MESSAGE, "抢先处理成功！");
        		}else{
        			result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
        			result.put(ResultMsgConstants.ERR_MSG, "状态错误，不能抢先处理！");
        		}
        	}else{
        		result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_ERROR);
    			result.put(ResultMsgConstants.ERR_MSG, "预约信息不存在！");
    		}
        	
			return result;
		}catch (Exception e){
            logger.error(e.getMessage());
            throw new ServiceBizException(e.getMessage(), e);
        }
	}
	
}
